package ge.telasi.tasks.ui.user;

import ge.telasi.tasks.model.User;
import ge.telasi.tasks.ui.Platform;
import ge.telasi.tasks.ui.UIUtils;
import ge.telasi.tasks.ui.comp.CommonDialog;
import ge.telasi.tasks.ui.log.LoggerUtils;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * @author dimitri
 */
public class UserRelationEditDialog  extends CommonDialog {
    private UserTableBase tblBosses;
    private UserTableBase tblAssistants;
    private JButton btnClose;
    private User user;
    private JButton btnAddBoss;
    private JButton btnRemoveBoss;
    private JButton btnAddAssistant;
    private JButton btnRemoveAssistant;

    public UserRelationEditDialog(Component parent) {
        super(parent, true);
        initComponents();
        setSize(700, 300);
        enableButtons();
    }

    private void initComponents() {
        getContentPane().setLayout(new BorderLayout(5, 5));
        JPanel mainPanel = new JPanel(new BorderLayout(5, 5));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        mainPanel.add(createCenterPanel(), BorderLayout.CENTER);
        mainPanel.add(createBottomPanel(), BorderLayout.SOUTH);
        getContentPane().add(mainPanel, BorderLayout.CENTER);
        getRootPane().setDefaultButton(btnClose);
    }

    private JComponent createCenterPanel() {
        JPanel centerPanel = new JPanel(new GridLayout(1, 2, 5, 5));
        centerPanel.add(createLeftComponent());
        centerPanel.add(createRightComponent());
        return centerPanel;
    }

    private JComponent createLeftComponent() {
        JPanel panel = new JPanel(new BorderLayout(0, 0));
        tblBosses = new UserTableBase();
        tblBosses.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tblBosses.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                enableButtons();
            }
        });
        panel.add(new JScrollPane(tblBosses), BorderLayout.CENTER);
        JLabel label = new JLabel("უფროსები:");
        label.setFont(UIUtils.makeBold(label.getFont()));
        panel.add(label, BorderLayout.NORTH);
        JToolBar toolbar = new JToolBar();
        panel.add(toolbar, BorderLayout.SOUTH);
        btnAddBoss = new JButton();
        btnRemoveBoss = new JButton();
        btnAddBoss.setIcon(UIUtils.getIcon16x16("add.png"));
        btnRemoveBoss.setIcon(UIUtils.getIcon16x16("delete.png"));
        btnAddBoss.setToolTipText("უფროსის დამატენა");
        btnRemoveBoss.setToolTipText("უფროსის წაშლა");
        btnAddBoss.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                onAddRelation(false);
            }
        });
        btnRemoveBoss.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                onRemoveRelation(false);
            }
        });
        toolbar.add(btnAddBoss);
        toolbar.add(btnRemoveBoss);
        toolbar.setFloatable(false);
        return panel;
    }

    private JComponent createRightComponent() {
        JPanel panel = new JPanel(new BorderLayout(0, 0));
        tblAssistants = new UserTableBase();
        tblAssistants.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        tblAssistants.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                enableButtons();
            }
        });
        panel.add(new JScrollPane(tblAssistants), BorderLayout.CENTER);
        JLabel label = new JLabel("ასისტენტები:");
        label.setFont(UIUtils.makeBold(label.getFont()));
        panel.add(label, BorderLayout.NORTH);
        JToolBar toolbar = new JToolBar();
        panel.add(toolbar, BorderLayout.SOUTH);
        btnAddAssistant = new JButton();
        btnRemoveAssistant = new JButton();
        btnAddAssistant.setIcon(UIUtils.getIcon16x16("add.png"));
        btnRemoveAssistant.setIcon(UIUtils.getIcon16x16("delete.png"));
        btnAddAssistant.setToolTipText("ასისტენტის დამატენა");
        btnRemoveAssistant.setToolTipText("ასისტენტის წაშლა");
        btnAddAssistant.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                onAddRelation(true);
            }
        });
        btnRemoveAssistant.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                onRemoveRelation(true);
            }
        });
        toolbar.add(btnAddAssistant);
        toolbar.add(btnRemoveAssistant);
        toolbar.setFloatable(false);
        return panel;
    }

    private JComponent createBottomPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        btnClose = new JButton("გასვლა");
        panel.add(btnClose, BorderLayout.EAST);
        btnClose.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });
        return panel;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
        setTitle(user.getFullName() + " (" + user.getUsername() + ") -- დამოკიდებულება");
    }

    public boolean refresh() {
        Platform pl = Platform.getDefault();
        if (pl.validateConnection()) {
            try {
                user = pl.getFacade().getUserWithRelations(pl.getCredentials(), user);
                tblBosses.display(user.getBosses());
                tblAssistants.display(user.getAssistants());
                enableButtons();
                return true;
            } catch (Exception ex) {
                LoggerUtils.manageException(this, ex);
            }
        }
        return false;
    }

    private void enableButtons() {
        boolean userSelected = user != null;
        boolean bossSelected = userSelected && tblBosses.getSelectedUser() != null;
        boolean assistantSelected = userSelected && tblAssistants.getSelectedUser() != null;
        btnAddBoss.setEnabled(userSelected);
        btnAddAssistant.setEnabled(userSelected);
        btnRemoveBoss.setEnabled(bossSelected);
        btnRemoveAssistant.setEnabled(assistantSelected);
    }

    private void onAddRelation(boolean assistant) {
        boolean userSelected = user != null;
        Platform pl = Platform.getDefault();
        if (userSelected && pl.validateConnection()) {
            UserPickDialog dialog = new UserPickDialog(this);
            dialog.refresh();
            UIUtils.openDialog(dialog);
            if (dialog.isApproved()) {
                try {
                    User updated = pl.getFacade().addUserRelation(pl.getCredentials(), user, dialog.getSelectedUsers(), assistant);
                    this.user = updated;
                    tblAssistants.display(user.getAssistants());
                    tblBosses.display(user.getBosses());
                } catch (Exception ex) {
                    LoggerUtils.manageException(this, ex);
                }
            }
        }
    }

    private void onRemoveRelation(boolean assistant) {
        List<User> users = assistant ? tblAssistants.getSelectedUsers() : tblBosses.getSelectedUsers();
        Platform pl = Platform.getDefault();
        if (users != null && !users.isEmpty() && pl.validateConnection()) {
            String msg = pl.getLocaleManager().getMessage("General.deleteByCountMsg", users.size());
            if (UIUtils.askConfirmation(this, msg)) {
                try {
                    user = pl.getFacade().removeUserRelation(pl.getCredentials(), user, users, assistant);
                    tblAssistants.display(user.getAssistants());
                    tblBosses.display(user.getBosses());
                } catch (Exception ex) {
                    LoggerUtils.manageException(this, ex);
                }
            }
        }
    }

}
